#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

class Solution
{
    vector<vector<int>> ret;
    vector<int> path;
    int sum, n;
public:
    vector<vector<int>> combinationSum2(vector<int>& candidates, int target)
    {
        n = candidates.size();
        sort(candidates.begin(), candidates.end());
        dfs(candidates, target, 0);
        return ret;
    }

    void dfs(vector<int>& candidates, int target, int pos)
    {
        if (sum == target)
        {
            ret.push_back(path);
            return;
        }

        for (int i = pos; i < n; i++)
        {
            if (i > pos && candidates[i] == candidates[i - 1])
            {
                continue;
            }
            else if (sum < target)
            {
                sum += candidates[i];
                path.push_back(candidates[i]);
                dfs(candidates, target, i + 1);
                path.pop_back();
                sum -= candidates[i];
            }
            else
            {
                return;
            }
        }
    }
};


int main()
{
    vector<int> candidates = { 10,1,2,7,6,1,5 };
    auto ret = Solution().combinationSum2(candidates, 8);
    for (auto& v : ret)
    {
        for (auto& e : v)
        {
            cout << e << " ";
        }
        cout << endl;
    }
    return 0;
}
